package com.ruoyi.partybuilding.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.partybuilding.common.*;
import lombok.var;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.partybuilding.domain.Files;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件信息Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "文件信息")
@RestController
@RequestMapping("/partybuilding/Files")
public class FilesController extends EQueryController<Files>
{

    @Resource
    protected EQueryHelper queryHelper;

    /**
     * 查询文件信息列表
     */
    @ApiOperation("分页")
    @GetMapping("query")
    @PreAuthorize("@ss.hasPermi('partybuilding:Files:list')")
    protected R<Page<Files>> list(Files entity, PageDomain pageRequest)
    {
       return queryPage(entity,pageRequest);
    }


    /**
     * 删除文件信息
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:Files:remove')")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
    @PostMapping("remove")
    public R remove(@RequestBody Files entity) {
        return remove(entity);
    }

    @PostMapping("/upload/{type}")
    public R<List<Files>> upload(@PathVariable(value = "type", required = true) String type,MultipartFile file) {
        var files = new ArrayList<MultipartFile>();
        files.add(file);
        return uploads(type, files);
    }
    @PostMapping("/uploads/{type}")
    public R<List<Files>> uploads(@PathVariable(value = "type", required = true) String type,List<MultipartFile> files){
        try
        {
            var dirBase=getTypeDir(type);
            if(dirBase==null)
                return R.fail("缺少文件分类信息");
            if(files==null||files.size()<1)
                return R.fail("缺少文件");
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath()+dirBase;
            var list=new ArrayList<Files>();
            var urlBase="";
            for (MultipartFile file : files)
            {
                var info=new Files();
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = urlBase + fileName;
                info.setName(FileUtils.getName(fileName));
                info.setExt(org.springframework.util.StringUtils.getFilenameExtension(file.getOriginalFilename()));
                info.setUrl(url);
                info.setSize(file.getSize());
                info.setRemark(file.getOriginalFilename());
                list.add(info);
            }
            queryHelper.query().insertable(list).executeRows();
            return R.ok(list);
        }
        catch (Exception e)
        {
            return R.fail(e.getMessage());
        }
    }


    String getTypeDir(String type){
        var arr=new String[]{"userpic","meeting","teampic","honorpic"};
        for (String dir : arr) {
            if(dir.equals(type))
                return "/"+dir;
        }
        return null;
    }

    @ApiOperation("通过id下载文件")
    @GetMapping("/download")
    public void download(Long id, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            var info= queryHelper.query().queryable(Files.class).where(p->p.eq(Files::getId,id)).firstOrNull();
            if (!FileUtils.checkAllowDownload(info.getName()))
            {
                throw new Exception(StringUtils.format("文件名称,不允许下载。 "));
            }
            String realFileName = System.currentTimeMillis() + info.getName().substring(info.getName().indexOf("_") + 1);
            String filePath =  info.getUrl();//RuoYiConfig.getDownloadPath() +

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e)
        {
            logger.error("下载文件失败", e);
        }
    }
}
